﻿using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.ObjectBuilder;
using Microsoft.Practices.ObjectBuilder2;
using System;

namespace UniAspect.UnityCommon.ResolutionLogging
{
    public class ResolutionLoggingExtension : UnityContainerExtension
    {
        private readonly IResolutionLoggerPolicy _logger;

        public ResolutionLoggingExtension()
                : this(null)
        {

        }

        public ResolutionLoggingExtension(IResolutionLoggerPolicy logger)
        {
            _logger = logger;
        }

        protected override void Initialize()
        {

            Context.Strategies.AddNew<ResolutionLoggingStrategy>(UnityBuildStage.Setup);
            if (_logger != null)
            {
                SetDefaultLogger(_logger);
            }
        }

        public ResolutionLoggingExtension SetDefaultLogger(IResolutionLoggerPolicy logger)
        {
            Context.Policies.SetDefault(logger);
            return this;
        }

        /// <summary>
        /// Add logger for specific build key
        /// </summary>
        public ResolutionLoggingExtension AddLogger(Type t, string name, IResolutionLoggerPolicy logger)
        {
            var key = new NamedTypeBuildKey(t, name);
            Context.Policies.Set(logger, key);
            return this;
        }

        public ResolutionLoggingExtension AddLogger<T>(IResolutionLoggerPolicy logger)
        {
            return AddLogger(typeof(T), null, logger);
        }

        public ResolutionLoggingExtension AddLogger<T>(string name, IResolutionLoggerPolicy logger)
        {
            return AddLogger(typeof(T), name, logger);
        }
    }
}